<?php
/*
    方倍工作室 http://www.cnblogs.com/txw1958/
    CopyRight 2013 www.doucube.com  All Rights Reserved
*/

define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $postStr=file_get_contents('php://input');
    $wechatObj->responseMsg($postStr);
}
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg($postStr)
    {
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $url =  trim($postObj->PicUrl);
            $time = time();
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            require_once 'facepp_sdk.php';
            $facepp = new Facepp();
            //$url=$postObj->PicUrl;
            $params=array('url'=>$url);
            $contentStr="对不起识别失败了！请稍后再试！";
            $response = $facepp->execute('/detection/detect',$params);
            if($response['http_code']==200){ 
                $data = json_decode($response['body'],1);
                $response = $facepp->execute("/recognition/compare?face_id2=".$data['face'][0]['face_id']."&face_id1=".$data['face'][1]['face_id']);
                $a=json_decode($response['body'],1);
                //var_dump($a['component_similarity']);
                $da=$a['component_similarity'];
                $ab=($da['eye']+$da['eyebrow']+$da['mouth']+$da['nose'])/4;
                $contentStr="你们的相似指数为：\n"."眼睛：".$da['eye']
                ."%\n眉毛：".$da['eyebrow']
                ."%\n嘴巴：".$da['mouth']
                ."%\n鼻子：".$da['nose']
                ."%\n平均指数：".$ab."%";
            }
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
        }
    }
}
?>
